$(function(){
    const data = localStorage.getItem('myTodolist')
    const list = data? JSON.parse(data):[]
    render()
    $('#title').on('keydown',function(e){
        if(e.key === 'Enter'){
            const text = $(this).val()
            if(text.trim() == '') return alert('请输入内容')
            // 将数据添加到数组
            list.push({
                title : text,
                done :false
            })
            localStorage.setItem('myTodolist', JSON.stringify(list))
            render()
            $(this).val('')
        }
    })
    // 渲染数据
    function render() {
        let todoCount = 0
        let doneCount = 0
        $('#donelist').empty()
        $('#todolist').empty()
        $.each(list, function (index, ele) { 
            if(ele.done == true){
                doneCount++
                const li = $(`<li data-index = ${index}><input type="checkbox" checked="checked"> <p>${ele.title}</p> <a href="javascript:;" id="0"></a></li>`)
                $('#donelist').append(li)  
            }else{
                todoCount++
                const li = $(`<li data-index = ${index}><input type="checkbox" > <p>${ele.title}</p> <a href="javascript:;" id="0"></a></li>`)
                $('#todolist').append(li)
            }
        });
        $('#todocount').html(todoCount)
        $('#donecount').html(doneCount)
    }
    // 点击进行的复选框
    $('ul,ol').on('change', 'input',function(){
        const status = $(this).prop('checked');
        const index = $(this).parent().attr('data-index');
        list[index].done = status
        localStorage.setItem('myTodolist', JSON.stringify(list))
        render()
    })
    // 删除
    $('ul,ol').on('click', 'a',function(){
        const index = $(this).parent().attr('data-index');
        list.splice(index, 1)
        localStorage.setItem('myTodolist', JSON.stringify(list))
        render()
    })
    
})